<template>
    <div
        class="ICcardTransqry"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <cardComponent pageTitle="IC卡电子现金消费明细查询">
            <template slot="cardBody">
                <!-- 搜索表单模块 -->
                <el-form
                    class="searchForm"
                    ref="searchForm"
                    :model="searchForm"
                    :rules="rules"
                    :inline="true"
                    label-position="right"
                    size="small"
                    label-width="110px"
                >
                    <el-row>
                        <el-form-item label="账户类别:" class="text_fl">
                            <el-select
                                v-model="searchForm.accttype"
                                placeholder="请选择账户类别"
                                clearable
                                @change="changeCardList"
                            >
                                <el-option
                                    v-for="item in AccountionTYPE_INFO"
                                    :label="item.label"
                                    :value="item.code"
                                    :key="item.label"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="卡号:" class="text_fl">
                            <el-select v-model="searchForm.cardno" placeholder="请选择卡号" clearable>
                                <el-option
                                    v-for="item in cardList"
                                    :label="item.CARDNBR"
                                    :value="item.CARDNBR"
                                    :key="item.CARDNBR"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="起始日期:" class="text_fl">
                            <el-date-picker
                                v-model="searchForm.startDate"
                                type="date"
                                placeholder="请选择起始日期"
                                value-format="yyyyMMdd"
                                format="yyyy-MM-dd"
                                :picker-options="startOptions"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="结束日期:" class="text_fl">
                            <el-date-picker
                                v-model="searchForm.endDate"
                                type="date"
                                placeholder="请选择结束日期"
                                value-format="yyyyMMdd"
                                format="yyyy-MM-dd"
                                :picker-options="endtOptions"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <div class="btn_Box">
                                <el-button
                                    type="primary"
                                    size="small"
                                    icon="el-icon-search"
                                    @click="handleGetListData('first')"
                                >查 询</el-button>

                                <el-button
                                    type="primary"
                                    size="small"
                                    icon="el-icon-refresh-right"
                                    @click="handleReset"
                                >重 置</el-button>
                            </div>
                        </el-form-item>
                    </el-row>
                </el-form>
                <div v-show="isShowTotal" class="box-card" style="padding: 0px;">
                    <el-row>
                        <el-col :span="12">
                            <div class="text item">
                                <span>
                                    可用余额：
                                    {{this.ICbalance}}
                                </span>
                            </div>
                        </el-col>
                        <el-col :span="11">
                            <div class="text item">
                                <span>
                                    上次更新日期：
                                    {{this.lastupd}}
                                </span>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <!-- 表格数据展示模块 -->
                <div v-show="isShowView">
                    <el-table
                        :data="tableData"
                        border
                        stripe
                        @row-click="handleSelectRow"
                        header-row-class-name="headerRow"
                        ref="showListTable"
                        class="heard-bg business_table"
                    >
                        <el-table-column label="交易日期">
                            <template slot-scope="scope">{{scope.row.TXNDATE}}</template>
                        </el-table-column>
                        <el-table-column label="记账日期">
                            <template slot-scope="scope">{{scope.row.OPDATE}}</template>
                        </el-table-column>
                        <el-table-column label="交易金额">
                            <template slot-scope="scope">{{scope.row.AMTFL}}{{scope.row.AMOUNT}}</template>
                        </el-table-column>
                        <el-table-column label="流水号">
                            <template slot-scope="scope">{{scope.row.TRCNBR}}</template>
                        </el-table-column>
                        <el-table-column label="商户类型">
                            <template slot-scope="scope">{{scope.row.MERTYP}}</template>
                        </el-table-column>
                        <el-table-column label="交易处理结果">
                            <template slot-scope="scope">{{scope.row.PROCRES |getResultFormat}}</template>
                        </el-table-column>
                        <el-table-column label="交易类型描述">
                            <template
                                slot-scope="scope"
                            >{{scope.row.TRANCODE| filterTRANTYPE(ICtrantypeList)}}</template>
                        </el-table-column>
                        <el-table-column label="受卡方名称地址">
                            <template slot-scope="scope">{{scope.row.CARDNME}}</template>
                        </el-table-column>
                    </el-table>
                    <!-- 话术 -->
                    <div class="hstable_wrap" v-if="speechList.length!=0">
                        <el-table
                            :data="speechList"
                            border
                            stripe
                            header-row-class-name="headerRow"
                            ref="showListTable"
                            class="heard-bg business_table hstable"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                            <el-table-column label="业务话术">
                                <template slot-scope="scope">{{scope.row.content}}</template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="footer">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('pre')"
                            :disabled="currentPageIndex <= 0"
                        >上一页</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('next')"
                            :disabled="!nextButtonFlag"
                        >下一页</el-button>
                    </div>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
import moment from 'moment';
import { mapState } from 'vuex';
import { trimString, getDictSelectList } from '@/utils/Common';
import { LOANSTATUS_DAILYBASIS } from '@/utils/Contants';
import cardComponent from '@/components/cardComponent/cardComponent.vue';

export default {
    name: 'ICcardTransqry',
    components: {
        cardComponent,
    },
    data() {
        return {
            pageLoading: false, // 页面loading
            nextButtonFlag: false, // 下翻页按钮 显示控制阀

            searchForm: { // 搜索表单字段
                startDate: moment(new Date(new Date().getTime() - (1000 * 60 * 60 * 24 * 365))).format('YYYYMMDD'), // 开始日期 默认为当前日期往前一个月
                endDate: moment(new Date()).format('YYYYMMDD'), // 结束日期 默认为当前日期
                accttype: '',
                cardno: '',
            },
            ICtrantypeList: [],

            //transTotalObj: {},//交易汇总信息
            ICbalance: '',
            lastupd: '',
            tableData: [],
            rules: { // 表单校验规则
                startDate: [
                    { required: true, message: '请选择起始日期', trigger: 'blur' },
                ],
                endDate: [
                    { required: true, message: '请选择结束日期', trigger: 'blur' },
                ],
            },
            startOptions: { // 开始日期选择 限制
                disabledDate: (time) => {
                    if (this.searchForm.endDate) {
                        return time.getTime() > new Date(moment(this.searchForm.endDate).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },
            endtOptions: { // 结束日期选择限制
                disabledDate: (time) => {
                    if (this.searchForm.startDate) {
                        return time.getTime() < new Date(moment(this.searchForm.startDate).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },
            currentSelectRow: '', //
            currentRowData: '', // 当前选择行的数据
            trialData: {}, // 试算结果数据
            pagingDataList: [], // 翻页上送字段列表
            currentPageIndex: 0, // 当前页
            isShowTotal: false,
            isShowView: false,
            cardList: [],
            speechList: [],//话术列表
            selectedList: [],
            MenuId: '',
        };
    },



    // 取缓存信息
    computed: mapState({
        cardInfo_3004: state => state.common.cardInfo_3004, // 默认卡信息
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        pinFlag: state => state.common.pinFlag, // 是否密码检查标志
        AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
        cardList_3601: state => state.common.cardList_3601, //卡列表
        isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
    }),

    filters: {
        // 状态 转译
        getStatusText(val) {
            let text = '';
            LOANSTATUS_DAILYBASIS.forEach((item) => {
                if (item.value === trimString(val)) {
                    text = item.label;
                }
            });
            return text;
        },
        // 取卡号后四位
        getFormatCard(val) {
            let card4end = ''
            card4end = val.trim()
            card4end = card4end.substring(card4end.length - 4)
            return card4end
        },
        // 格式化金额
        getFormatAmt(val) {
            let card4end = ''
            card4end = val.trim()
            card4end = card4end.substring(card4end.length - 4)
            return card4end
        },
        // 日期格式化
        getDateFormat(val) {
            if (val) {
                return moment(`${val}`).format('YYYY-MM-DD');
            }
            return '--';
        },

        filterTRANTYPE: (value, ICtrantypeList) => {
            value = (`${value}`).trim();
            for (let index = 0; index < ICtrantypeList.length; index++) {
                const element = ICtrantypeList[index];
                if (element.code === value) {
                    return element.label;
                }
            }
        },
        // 交易结果格式化
        getResultFormat(val) {

            if (val === 0) {
                return '成功';
            } else if (val === 1) {
                return '交易密文验证失败';
            } else if (val === 2) {
                return '交易金额大于当前可用余额';
            }
            return val;
        },
    },
    async mounted() {
        this.MenuId = this.$route.params.id || '';
        this.ICtrantypeList = await getDictSelectList('ICTRANS_TYPE', this);
        this.init();
        this.changeCardList(this.cardInfo_3004.CATEGORY + '');
        await this.getspeechList();
    },
    methods: {

        init() {
            console.log("默认账户类别：" + this.cardInfo_3004.CATEGORY);
            console.log("默认账户：" + this.cardInfo_3004.CARDNO);
            this.searchForm.accttype = this.cardInfo_3004.CATEGORY + '';

            //this.searchForm.cardno = this.cardInfo_3004.CARDNO;
        },
        changeCardList(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === val) {
                    this.cardList.push(item);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }
            });

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.searchForm.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.searchForm.cardno = this.cardList[0].CARDNBR;
            }


        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            console.log("this.MenuId", this.MenuId);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        // 点击查询 获取初始化列表数据
        /**
         * 交易代码：3096-IC卡交易明细查询
         * 
         */
        handleGetListData(type) {

            console.log("翻页查询标志：" + type);

            this.$refs.searchForm.validate(async (valid) => {
                if (valid) {
                    this.pageLoading = true;
                    // 设置请求参数 -- 3096 交易
                    let CENDT = '';
                    let TRCNBR = '';
                    let ACQNO = '';
                    let FORNO = '';
                    let TXNDATE = '';
                    let OPDATE = '';
                    let OPTIME = '';
                    if (type != 'first') {
                        if (this.pagingDataList.length) { // 判断翻页上传字段取值

                            CENDT = this.pagingDataList[this.currentPageIndex].CENDT;
                            TRCNBR = this.pagingDataList[this.currentPageIndex].TRCNBR;
                            ACQNO = this.pagingDataList[this.currentPageIndex].ACQNO;
                            FORNO = this.pagingDataList[this.currentPageIndex].FORNO;
                            TXNDATE = this.pagingDataList[this.currentPageIndex].TXNDATE;
                            OPDATE = this.pagingDataList[this.currentPageIndex].OPDATE;
                            OPTIME = this.pagingDataList[this.currentPageIndex].OPTIME;
                        }
                    } else {
                        this.currentPageIndex = 0;
                        this.pagingDataList = [];
                    }
                    const appBody = {
                        OPTION: 'A', // 查询方式 1-用卡号查询 2-用证件号码查询
                        CARDNBR: this.searchForm.cardno, // 卡号
                        TRANTYPE: 'A', // 分期类型
                        OPERCODE: '0',//操作代码，0-全部返回，1-可提前还款的分期交易，2-可撤销的分期交易
                        PINFLAG: this.pinFlag, // 是否检查密码标志 0-不检查
                        STDATE: this.searchForm.startDate, // 起始日期 YYYYMMDD
                        ENDDTE: this.searchForm.endDate, // 终止日期
                        RTNIND: this.pagingDataList.length === 0 ? '' : 1, // 翻页标志 首次传空， 翻页传1
                        CENDT, // 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的交易传输时间
                        TRCNBR, // 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的系统跟踪号
                        ACQNO,// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的代理机构标识码
                        FORNO,// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的发送机构标识码
                        TXNDATE,// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的交易日期
                        OPDATE,// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的登记日期
                        OPTIME// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的登记时间
                    };
                    const params = JSON.parse(JSON.stringify(this.defaultParams));
                    // console.log(this.defaultParams, 'this.defaultParams')
                    params.body.appHead.tranCode = '3096';
                    params.body.appBody = appBody;

                    // 跑 3096 交易
                    await this.$post.common.transPort(params).then((res) => {
                        this.pageLoading = false;
                        if (res.status === 200) {
                            this.isShowTotal = true;
                            this.isShowView = true;
                            const result = JSON.parse(res.data.jsonRes);
                            console.log(result, '响应数据 -- 3096');
                            //this.transTotalObj = result.body.appBody;

                            this.ICbalance = parseFloat(result.body.appBody.BALANCE).toFixed(2);
                            this.lastupd = result.body.appBody.LSTUPDATE;
                            //console.log(this.transTotalObj, '3096body');
                            if (result.sysHead.rspCd === '000000') {
                                this.tableData = result.body.appBody.dataList || [];
                                const currentPagingData = {
                                    CENDT: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].CENDT,
                                    TRCNBR: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].TRCNBR,
                                    ACQNO: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].ACQNO,
                                    FORNO: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].FORNO,
                                    TXNDATE: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].TXNDATE,
                                    OPDATE: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].OPDATE,
                                    OPTIME: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].OPTIME,
                                };
                                this.nextButtonFlag = !(result.body.appBody.RTNIND === '0');
                                let flag = false;
                                let currentIndex;
                                this.pagingDataList.forEach((item, index) => { // 判断此次查询数据最后一条记翻页分期付款序号是否在已有列表中
                                    if (item.TRCNBR === currentPagingData.TRCNBR) {
                                        flag = true;
                                        currentIndex = index;
                                    }
                                });
                                if (flag) { // 存在
                                    this.currentPageIndex = currentIndex;
                                } else {
                                    this.pagingDataList.push(currentPagingData);
                                    this.currentPageIndex = this.pagingDataList.length - 1;
                                }
                                console.log("this.pagingDataList:", this.pagingDataList);
                            } else {
                                //this.transTotalObj = {};
                                this.tableData = [];
                                this.currentPageIndex = 0;
                                this.pagingDataList = [];
                                this.nextButtonFlag = false;
                                // const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                                // this.$alert(errorMsg, '提示', {
                                //     customClass: 'error', type: 'error',
                                // });

                            }
                        } else {
                            // this.$alert('请求失败!', '提示', {
                            //     customClass: 'error', type: 'error',
                            // });
                        }
                    });
                } else {
                    this.pageLoading = false;
                }
            });
        },

        // 点击重置搜索表单
        handleReset() {
            this.searchForm.startDate = moment(new Date(new Date().getTime() - (1000 * 60 * 60 * 24 * 365))).format('YYYYMMDD');
            this.searchForm.endDate = moment(new Date()).format('YYYYMMDD');
            // 清空当前选择行数据
            this.currentRowData = '';
            // 清空缓存翻页数据
            this.pagingDataList = [];
            // this.handleGetListData()
        },

        handleChange(row) {
            // console.log(this.$refs[row.MPNO], 'this.$refs[row.MPNO]')
            // this.$refs[row.MPNO].getElementsByTagName('input').blur()

            this.handleSelectRow(row);
        },

        // 选择表格行
        handleSelectRow(row) {
            // console.log(row, '第' + row.MPNO + '行数据')
            // if (row.MPNO === this.currentSelectRow) {
            //     this.currentSelectRow = ''
            //     this.currentRowData = ''
            // } else {
            // }
            this.currentSelectRow = row.MPNO;
            this.currentRowData = row;
        },

        // 上下页切换
        handleChangePage(type) {
            // 翻页之前先清空 当前选择行数据
            this.currentRowData = '';
            if (type === 'pre') { // 切换到上一页
                if (this.currentPageIndex - 2 < 0) {
                    this.pagingDataList = []; // 清空缓存 申请编号 -> 相当于首次查询
                } else {
                    this.currentPageIndex = this.currentPageIndex - 2;
                }
                this.handleGetListData(type);
            } else { // 切换到下一页
                this.handleGetListData(type);
            }
        },

        // 关闭对话框
        handleCloseDialog() {
            this.isShowTrialDialog = false;
        },
        handleAdjust() {
            const appBody = {
                bankid: '6440', // 查询方式 1-用卡号查询 2-用证件号码查询
                num: '14', // 卡号

                Card: '6258280190001010',//操作代码，0-全部返回，1-可提前还款的分期交易，2-可撤销的分期交易
                acct: '0', // 是否检查密码标志 0-不检查
                limit_request_bef_days: '-9999', // 起始日期 YYYYMMDD
                templimit_reqyest_bef_days: '-9999', // 终止日期
                limit_adjust_bef_days: '-9999', // 翻页标志 首次传空， 翻页传1
                templimit_adjust_bef_days: '-9999', // 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的交易传输时间
                Channel: 'KF', // 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的系统跟踪号
                flag: '21',// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的代理机构标识码
                AdjustType: '2',// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的发送机构标识码
                AdjustReason: '1',// 首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的交易日期

            };
            const params = JSON.parse(JSON.stringify(this.defaultParams));
            // console.log(this.defaultParams, 'this.defaultParams')
            params.body.appHead.tranCode = '8001';
            params.body.appBody = appBody;

            // 跑 3096 交易
            this.$post.common.adjustlimit(params).then((res) => {
                this.pageLoading = false;
                if (res.status === 200) {
                    this.isShowTotal = true;
                    this.isShowView = true;
                    const result = JSON.parse(res.data.jsonRes);
                    console.log(result, '响应数据 -- 3096');
                    if (result.resultCode === 'T000') {
                        this.$alert("查询成功！", '提示', {
                            customClass: 'info',
                        });

                    } else {

                        const errorMsg = `错误代码：${result.resultCode}, 错误信息：${result.resultCode}`;
                        this.$alert(errorMsg, '提示', {
                            customClass: 'error', type: 'error',
                        });

                    }
                } else {
                    this.$alert('请求失败!', '提示', {
                        customClass: 'error', type: 'error',
                    });
                }
            });

        }
    },
};
</script>

<style scoped lang="scss">
.ICcardTransqry {
    .buttonBox {
        margin: 30px 0;
        text-align: right;
    }

    .footer {
        text-align: center;
        margin-top: 30px;
    }
    .tabletitle {
        width: 100%;
        text-align: center;
        color: #fff;
        background-color: #409eff;
        line-height: 36px;
        border-radius: 6px;
        .span {
            margin-left: 8px;
        }
    }
    .item {
        margin-bottom: 12px;
        color: #111;
        margin: 10px 0 15px 15px;
        border: #999;
    }
    .itme-text {
        display: inline-block;
        text-align: right;
        width: 35%;
        color: #111;
        margin-right: 15px;
    }
}

.trialDialog {
    .el-row {
        margin-bottom: 30px;

        .infoItem {
            .title {
                font-weight: 600;
                padding-right: 10px;
            }

            .info {
                color: #999;
            }
        }
    }
}
</style>
<style lang="scss">
.ICcardTransqry {
    .btn_Box {
        width: 250px;
        text-align: center;
    }
}
</style>